/**
 * @file 快捷键默认值与合并工具（共享）
 * 设计要点：
 * - 单一事实来源：默认快捷键仅在 getDefaultShortcutGroups 中定义
 * - getDefaultShortcuts 由分组扁平化得到，避免重复配置
 * - applyOverridesToShortcuts 将 overrides（仅存差异）合并为“有效快捷键”
 */

import type { CommandId, Shortcut } from '~types/global-state'
import { LANGUAGE_CONFIG, type SupportedLanguage } from '~shared/constants'

export type { CommandId } from '~types/global-state'
/**
 * 取当前语言的安全值（不合法时回退到默认语言）
 */
function ensureLang(lang?: string): SupportedLanguage {
  const supported = LANGUAGE_CONFIG.SUPPORTED_LANGUAGES as readonly string[]
  return supported.includes(lang ?? '')
    ? (lang as SupportedLanguage)
    : (LANGUAGE_CONFIG.DEFAULT_LANGUAGE as SupportedLanguage)
}

/**
 * 根据语言返回快捷键的名称与分组标题标签
 */
function getShortcutLabels(lang: SupportedLanguage) {
  if (lang === 'zhHans') {
    return {
      group: {
        tab: '标签页操作',
        edit: '编辑操作',
        settings: '设置',
        dev: '开发与调试'
      },
      name: {
        newTab: '新建标签页',
        closeTab: '关闭标签页',
        reload: '刷新页面',
        find: '在页面中查找',
        devtools: '切换开发者工具',
        settings: '打开设置'
      }
    }
  }
  return {
    group: {
      tab: 'Tab Actions',
      edit: 'Edit',
      settings: 'Settings',
      dev: 'Developer'
    },
    name: {
      newTab: 'New Tab',
      closeTab: 'Close Tab',
      reload: 'Reload',
      find: 'Find in Page',
      devtools: 'Toggle Developer Tools',
      settings: 'Open Settings'
    }
  }
}

/**
 * 生成当前平台的默认快捷键列表（供首次运行或重置时使用）。
 * - 会根据 macOS/Windows/Linux 差异选择不同修饰键（Cmd/Ctrl、Alt 等）
 * - 保持与主进程命令分发一致，以确保可用性
 * @param lang      语言（默认为当前语言）
 * @returns 默认快捷键配置数组
 */

export function getDefaultShortcuts(lang?: SupportedLanguage | string): Shortcut[] {
  // 单一事实来源：以“分组默认值”为准，平铺得到默认列表，避免重复维护
  const groups = getDefaultShortcutGroups(lang)
  return groups.flatMap(g => g.items)
}

export type ShortcutCategoryId = 'tab' | 'edit' | 'settings' | 'dev'

export interface ShortcutCategory {
  id: ShortcutCategoryId
  title: string
  items: Shortcut[]
}

/**
 * 生成带分类的默认快捷键结构
 */
export function getDefaultShortcutGroups(lang?: SupportedLanguage | string): ShortcutCategory[] {
  const labels = getShortcutLabels(ensureLang(lang))
  const groups: ShortcutCategory[] = [
    {
      id: 'tab',
      title: labels.group.tab,
      items: [
        { id: 'cmd:tab:new', name: labels.name.newTab, key: `CmdOrCtrl+T`, enabled: true },
        { id: 'cmd:tab:close', name: labels.name.closeTab, key: `CmdOrCtrl+W`, enabled: true },
        { id: 'cmd:tab:reload', name: labels.name.reload, key: `CmdOrCtrl+R`, enabled: true }
      ]
    },
    {
      id: 'edit',
      title: labels.group.edit,
      items: [{ id: 'cmd:find:toggle', name: labels.name.find, key: `CmdOrCtrl+F`, enabled: true }]
    },
    {
      id: 'settings',
      title: labels.group.settings,
      items: [
        { id: 'cmd:settings:open', name: labels.name.settings, key: `CmdOrCtrl+,`, enabled: true }
      ]
    },
    {
      id: 'dev',
      title: labels.group.dev,
      items: [{ id: 'cmd:devtools:toggle', name: labels.name.devtools, key: 'F12', enabled: true }]
    }
  ]
  return groups
}

/** 将 overrides 应用到默认列表，得到“有效快捷键列表” */
export function applyOverridesToShortcuts(
  defaults: Shortcut[],
  overrides: Record<CommandId, string> | undefined
): Shortcut[] {
  if (!overrides || Object.keys(overrides).length === 0) return defaults.slice()
  return defaults.map(s => {
    const ov = overrides[s.id]
    if (!ov) return s
    return {
      ...s,
      key: ov ?? s.key
    }
  })
}

/**
 * 获取“有效快捷键平铺列表”：默认值 + 用户差异
 */
export function getEffectiveShortcuts(
  overrides: Record<CommandId, string> | undefined,
  lang?: SupportedLanguage | string
): Shortcut[] {
  const defaults = getDefaultShortcuts(lang)
  return applyOverridesToShortcuts(defaults, overrides)
}

/** 获取“有效快捷键分组结构”：默认分组 + 用户差异 */
export function getEffectiveShortcutGroups(
  overrides: Record<CommandId, string> | undefined,
  lang?: SupportedLanguage | string
): ShortcutCategory[] {
  const groups = getDefaultShortcutGroups(lang)
  return groups.map(g => ({
    ...g,
    items: applyOverridesToShortcuts(g.items, overrides)
  }))
}
